import { ProForm, ProFormText } from "@ant-design/pro-components";
import { history } from "@umijs/max";
import { Button } from "antd";
import { login , getUserInfo } from '@/services/common'
import Cookies from "js-cookie";
import { useRef, useState } from "react";
import logo from '../../../public/images/logo.png'
import "./index.less";
import userAPI from "mock/userAPI";

const Login = () => {
  const formRef = useRef<any>();
  const [loginLoad, setLoginLoad] = useState(false);
  const [loginBtn, setLoginBtn] = useState(true);
  // 监听
  const handleMonitorValues = () => {
    const targetValue: any = formRef.current?.getFieldsFormatValue?.();
    let targetLoginBtn = false;
    let tempLength = 2;
    if (Object.keys(targetValue).length === tempLength) {
      for (const key in targetValue) {
        if (!targetValue[key].trim()) {
          targetLoginBtn = true;
          break;
        }
      }
    } else {
      targetLoginBtn = true;
    }
    if (targetLoginBtn !== loginBtn) {
      setLoginBtn(targetLoginBtn);
    }
  };

  // 登录
  const toLogin = async (values: any) => {
    setLoginLoad(true);
    try {
      const sendData = {
        ...values,
      };
      if (!sendData.uuid) {
        delete sendData.uuid;
      }
      let targetSendData = sendData;
      const res = await login(targetSendData);
      
      if(res?.code === 200){
        Cookies.set("Token", res.data?.tokenValue);
        const userInfoRes = await getUserInfo({
          userId: res?.data?.loginId,
        });
        if (userInfoRes?.code === 200) {
          window.sessionStorage.setItem(
            "userInfo",
            JSON.stringify(userInfoRes?.data)
          );
        }
        setLoginLoad(false);
        initSystemData();
      }
    } catch (error) {
      setLoginLoad(false);
      return;
    }
  };
  // 初始化系统接口
  const initSystemData = async () => {
    const urlParams = new URL(window.location.href).searchParams;
    setLoginLoad(false);
    history.push(urlParams.get("redirect") || "/");
  };
  const handleKeyUp = (event: any) => {
    if (event.key === "Enter") {
      formRef?.current?.submit?.();
    }
  };

  return (
    <div className="login-wrapper">
      <div className="header-wrapper">
        <div className="header-left">
          <img src={logo} alt="" />
          <span>中央监护系统</span>
        </div>
      </div>
      <div className="contain-wrapper">
        <div className="form-wrapper">
          <div className="header-title">用户登录</div>
          <ProForm
            formRef={formRef}
            submitter={{
              render: (props: any) => {
                return [
                  <Button
                    loading={loginLoad}
                    disabled={loginBtn}
                    className="login-btn"
                    key="submit"
                    onClick={() => props.form?.submit?.()}
                  >
                    登录
                  </Button>,
                ];
              },
            }}
            onFinish={toLogin}
            onValuesChange={handleMonitorValues}
          >
            <ProFormText
              name="username"
              label="用户名"
              placeholder="请输入用户名"
              fieldProps={{
                onKeyUp: handleKeyUp,
              }}
            />
            <ProFormText.Password
              label="密码"
              name="password"
              placeholder="请输入密码"
              fieldProps={{
                onKeyUp: handleKeyUp,
              }}
            />
          </ProForm>
        </div>
      </div>
      {/* 底部版权信息 */}
      <div className="copyright-wrapper">
        <a className="desc" href="https://beian.miit.gov.cn/" target="_black">
          中船海神医疗科技有限公司
        </a>
      </div>
    </div>
  );
};

export default Login;
